<template>
  <div class="write-container">
    <div v-if="!isHide">
      <h1 id="inActiveTime" style="display: none;" />
      <div v-cloak v-if="writeStatus==0">
        <el-result :title="writeNotStartPrompt" icon="error" />
      </div>
      <div v-cloak v-if="writeStatus==3">
        <el-card class="pwdinput-card text-center">
          <div slot="header" class="clearfix">
            <span> 请输入密码填写</span>
          </div>
          <el-input v-model="writePassword" placeholder="请输入密码填写" />
          <el-button class="width50 mt20 " type="primary" @click="handleCheckWritePwd">
            确定
          </el-button>
        </el-card>
      </div>
      <div v-if="writeStatus==1 && start" class="form-container">
        <biz-project-form
          v-if="formConfig.formKey"
          ref="bizProjectForm"
          :form-config="formConfig"
          @submit="submitForm"
          @completed="handleFormLoadCompleted"
        />
          
        <!--    商品支付-->
        <goods-pay ref="goodsPay" @paySuccess="submitForm" />
      </div>
      <div v-cloak v-if="writeStatus==2" class="title-icon-view">
        <div v-if="userFormSetting.submitShowType===2" v-html="userFormSetting.submitShowCustomPageContent" />

        <el-result v-else :title="'提交成功！'"
                   icon="success"
        />
        <div v-if="submitResult.randomNumberText">
          {{ submitResult.randomNumberText }}
          <el-button v-clipboard:copy="submitResult.randomNumberText" v-clipboard:error="()=>{msgError('复制失败')}"
                     v-clipboard:success="()=>{msgSuccess('复制成功')}"
                     type="text"
                     class="pl10"
          >
            复制
          </el-button>
        </div>
        <div v-if="submitResult.examScoreText">
          {{ submitResult.examScoreText }}
        </div>
      </div>
      <div v-if="writeStatus==4" class="title-icon-view">
        <el-result :title="'已提交过数据，不可重复提交!'"
                   icon="error"
        />
      </div>
      <div v-if="writeStatus==5" class="title-icon-view">
        <el-result :title="'验证码仅可获取一次，已获取一次，无法再获取。'"
                   icon="error"
        />
      </div>
      <div v-if="writeStatus==6" class="title-icon-view">
        <el-result :title="'您输入的链接错误，请重新输入正确的链接'"
                   icon="error"
        />
      </div>
      <div v-if="writeStatus==7" class="title-icon-view">
        <el-result :title="'该链接已答题成功，请勿重复提交'"
                   icon="error"
        />
      </div>
    </div>
    
    <el-dialog title="验证" :visible.sync="dialogFormVisible" append-to-body :show-close="false" width="95%" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" :disabled="phoneDisabled" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="!isHideCode" label="验证码" prop="loginCdde">
          <el-input v-model="form.loginCdde" autocomplete="off" style="width:40%" />
          <el-button :disabled="canLogin || second>0" style="margin-left:5px" @click="getCode">
            获取验证码<span v-if="second>0 ">{{ second }}</span>
          </el-button>
        </el-form-item>
      </el-form>
      <p v-if="!isHideCode" class="tip">
        <i class="el-icon-warning" />验证码仅可获取一次，时效两分钟，请谨慎操作
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="canLogin" @click="login">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-backtop target=".write-container">
      <div style="font-size:12px;text-align: center;">
        <div class="el-icon-arrow-up" />
        <div>顶部</div>
      </div>
    </el-backtop>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import BizProjectForm from '@/formgen/src/components/BizProjectForm'
import GoodsPay from "./GoodsPay"
import {getQueryString} from '@/utils'
import constants from '@/utils/constants'
import {removeFormData} from "@/formgen/src/utils/db"
import {getAuthorizationUrl, getAuthorizationUserInfo, getWxSignature} from '@/api/project/wxmp'
import {isWxEnv, onlyWxOpenHandle, setWxConfig} from './wx'
import TduckFormMixin from '../TduckFormMixin'
import ExpandMixin from './ExpandMixin'
import {createFormResultRequest, publicCreateFormResultRequest, viewFormResultRequest,updatePhone} from '@/api/project/data'
import {
  checkWritePwdRequest,
  getPublicSettingsRequest,
  getWriteSettingStatusRequest,
  getFormPhoneNumber,
  sendCode,
  userFormLogin,
  isNeedLogin,
  checkYbkInfo
} from '@/api/project/setting'

const uaParser = require('ua-parser-js')
const ua = uaParser(navigator.userAgent)

require('@/utils/ut')

export default {
  name: 'WriteView',
  components: {
    BizProjectForm,
    GoodsPay
  },
  mixins: [TduckFormMixin, ExpandMixin],
  props: {
    // 1：公开填写 2：指定成员填写
    writeType: {
      type: Number,
      default: 1
    }
  },
  data() {
    let handlePhone = (rule, value, callback) => {
      if (value) {
        var validator = '^1[3-9][0-9]{9}$'
        if (!new RegExp(validator).test(value)) {
            this.canLogin=true
            callback(new Error('请输入正确的手机号'))
          } else {
            this.canLogin=false
            callback()
          }
      } else {
        this.canLogin=true
        callback(new Error("请输入手机号"))
      }
    }
    return {
      formKey: '',
      writePassword: '',
      inActiveTime: 0,
      formConfig: {
        formKey: '',
        preview: false,
        showBtns: true,
        submitPhoneNumber:''
      },
      writeStatus: 1,
      // 不允许填写的提示信息
      writeNotStartPrompt: '',
      userFormSetting: {},
      // 微信授权地址
      wxAuthorizationUrl: '',
      wxAuthorizationCode: '',
      wxUserInfo: {},
      wxSignature: {},
      //待提交问卷数据
      submitFormData: {
        completeTime: null,
        formKey: null,
        submitOs: ua.os.name,
        submitBrowser: ua.browser.name,
        submitUa: ua,
        wxUserInfo: null,
        wxOpenId: null,
        originalData: null,
        submitPhoneNumber:''
      },
      // 提交后返回的数据
      submitResult: {
        //随机编号
        randomNumberText: '',
        //考试成绩
        examScoreText: ''
      },
      form:{
        phoneNumber:'',
        loginCdde:''
      },
      rules: {
        phoneNumber: [
            { trigger: 'change',validator:handlePhone },
          ],
      },
      second:0,
      num:0,
      dialogFormVisible:false,
      isHide:false,
      phoneDisabled:false,
      start:false,
      canLogin:true,
      isHideCode:true,
      interval:null,
      formDataId:'',
      statusFlag:''
    }
  },
  async created() {
    this.formKey = this.$route.query.key || this.$route.params.key
    let ybk = getQueryString('ybk')
    if(ybk){
      checkYbkInfo({ybk:ybk}).then((res) => {
        console.log(res,'66666')
        if(res.code == 200){
          this.formConfig.submitPhoneNumber=res.data
          this.start=true
        }else if(res.code == 503){
          this.writeStatus=6
        }else if(res.code == 504){
          this.writeStatus=7
        }
      })
    }else{
      let ext = getQueryString('ext')
      console.log(ext,'ext')
      var numreg = /^[0-9]*$/
      var numre = new RegExp(numreg)
      await isNeedLogin({formKey:this.formKey}).then((res) => {
        if(res.code == 200){
          this.statusFlag =res.data
          // 00：短信样本库都没开启
          // 01：短信没开启样本库开启
          // 10：短信开启样本库没开启
          // 11：短信样本都开启
          if(res.data == '00'){//直接答题,两个按钮都没打开
            this.dialogFormVisible=false
            this.start=true
          }else{  
            if(res.data == '01'){//短信没开启样本库开启
              this.isHideCode = true
            }else{
              this.isHideCode = false
            }
            if(res.data == '01' || res.data == '11'){//这次把10：短信开启样本库没开启放到后面处理了，其他情况一样放前面
              if(Cookies.get('isLogin')){
                let isLogin = JSON.parse(Cookies.get('isLogin'))
                if(isLogin && isLogin.phoneNumber){
                  this.formConfig.submitPhoneNumber=isLogin.phoneNumber
                }
                console.log(isLogin,'islogin')
                if(this.formKey == isLogin.formKey){
                  if(isLogin.ext){
                    if(ext){
                      if(isLogin.ext == ext){
                        this.dialogFormVisible=false
                      }else{
                        if(!numre.test(ext)) {
                          this.dialogFormVisible=false
                        }else{
                          this.dialogFormVisible=true
                        }
                      }
                    }else{
                      this.dialogFormVisible=false
                    }
                  }else{
                    if(ext){
                      //缓存是公开链接
                      if(!numre.test(ext)) {
                        // 单条链接
                        this.dialogFormVisible=false
                      }else{
                        //纯数字的是批量，批量的回显手机号
                        this.dialogFormVisible=true
                      }
                    }else{
                      this.dialogFormVisible=false
                    }
                    
                  }

                }else{
                  this.dialogFormVisible=true
                }
              }else{
                this.dialogFormVisible=true
              } 
              if(this.dialogFormVisible){
                this.start=false
              }else{
                this.start=true
              }
            }else{
              this.start=true
            }
          }
        
        }
      }) 

      if(ext){
        if(!numre.test(ext)) {
          // 单条链接
          this.phoneDisabled=false
        }else{
          //纯数字的是批量，批量的回显手机号
          await getFormPhoneNumber({ext:ext}).then((res) => {
            if(res.code == 200){
              this.form.phoneNumber=res.data
              this.phoneDisabled=true
              this.canLogin=false
            }
          })
        }
        
      }
    }
    
    let wxCode = getQueryString('code')
    // cookie获取微信用户信息
    this.getCookieAuthorizationUserInfo()
    // 微信授权重定向到该页 会携带code参数

    if (wxCode) {
      this.wxAuthorizationCode = wxCode
      await this.getWxAuthorizationUserInfo()
    }
    // 微信逻辑授权结束 授权地址
    this.getWxAuthorizationUrl()
    // 检查是否能进入填写
    this.queryProjectSettingStatus()
    // 查询相关设置 检查是否能打开等
    let settingRes = await this.queryProjectSetting()
    // 非微信环境不加载微信相关 加快访问速度
    if (constants.enableWx && isWxEnv()) {
      // 加载微信相关 获取签名
      getWxSignature({url: window.location.href}).then((res) => {
        this.wxSignature = res.data
        setWxConfig(this.wxSignature, settingRes.data)
      })
    }
    viewFormResultRequest(this.formKey).then(() => {
    })
  },
  methods: {
    isNeedLoginFun(){
      let ext = getQueryString('ext')
      console.log(ext,'ext')
      var numreg = /^[0-9]*$/
      var numre = new RegExp(numreg)
      isNeedLogin({formKey:this.formKey}).then((res) => {
        if(res.code == 200){ 
            if(res.data == '10'){
              this.isHideCode = false
            
              if(Cookies.get('isLogin')){
                let isLogin = JSON.parse(Cookies.get('isLogin'))
                if(isLogin && isLogin.phoneNumber){
                  this.formConfig.submitPhoneNumber=isLogin.phoneNumber
                }
                console.log(isLogin,'islogin')
                if(this.formKey == isLogin.formKey){
                  if(isLogin.ext){
                    if(ext){
                      if(isLogin.ext == ext){
                        this.dialogFormVisible=false
                      }else{
                        if(!numre.test(ext)) {
                          this.dialogFormVisible=false
                        }else{
                          this.dialogFormVisible=true
                        }
                      }
                    }else{
                      this.dialogFormVisible=false
                    }
                  }else{
                    if(ext){
                      //缓存是公开链接
                      if(!numre.test(ext)) {
                        // 单条链接
                        this.dialogFormVisible=false
                      }else{
                        //纯数字的是批量，批量的回显手机号
                        this.dialogFormVisible=true
                      }
                    }else{
                      this.dialogFormVisible=false
                    }
                    
                  }

                }else{
                  this.dialogFormVisible=true
                }
              }else{
                this.dialogFormVisible=true
              }
            }
        }
      }) 

      if(ext){
        if(!numre.test(ext)) {
          // 单条链接
          this.phoneDisabled=false
        }else{
          //纯数字的是批量，批量的回显手机号
          getFormPhoneNumber({ext:ext}).then((res) => {
            if(res.code == 200){
              this.form.phoneNumber=res.data
              this.phoneDisabled=true
              this.canLogin=false
            }
          })
        }
        
      }
      
    },
    queryProjectSettingStatus() {
      // 是否能进入填写
      getWriteSettingStatusRequest({
        formKey: this.formKey,
        type: this.writeType,
        wxOpenId: this.wxUserInfo ? this.wxUserInfo.openid : ''
      }).then((res) => {
        if (res.msg) {
          this.writeNotStartPrompt = res.msg
          this.writeStatus = 0
        }
      })
    },
    getCookieAuthorizationUserInfo() {
      // cookie缓存拿一次 没有的话调接口拿
      let wxUserInfo = Cookies.get('wxUserInfo')
      if (wxUserInfo) {
        wxUserInfo = JSON.parse(wxUserInfo)
        console.log(wxUserInfo)
        if (wxUserInfo.openid) {
          this.wxUserInfo = wxUserInfo
        }
      }
    },
    getWxAuthorizationUserInfo() {
      // 根据code 获取用户授权信息
      let wxAuthorizationCode = this.wxAuthorizationCode
      return getAuthorizationUserInfo({
        code: wxAuthorizationCode
      }).then((res) => {
        if (res.data) {
          console.log('wxuser')
          this.wxUserInfo = res.data
          Cookies.set('wxUserInfo', JSON.stringify(res.data))
          console.log(this.wxUserInfo)
        }
      })
    },
    getWxAuthorizationUrl() {
      // 获取微信授权url地址
      getAuthorizationUrl({url: window.location.href}).then((res) => {
        if (res.data) {
          this.wxAuthorizationUrl = res.data
        }
      })
    },
    async queryProjectSetting() {
      // 填写设置
      let res = await getPublicSettingsRequest(this.formKey)
      this.formConfig.formKey = this.formKey
      if (res.data) {
        this.userFormSetting = res.data
        this.formConfig.setting = res.data
        // 仅在微信环境打开
        if (res.data && res.data.onlyWxWrite) {
          // 记录微信用户信息
          if (res.data.recordWxUser && !this.wxAuthorizationCode) {
            if (Object.keys(this.wxUserInfo).length === 0) {
              location.href = this.wxAuthorizationUrl
            }
          } else {
            onlyWxOpenHandle()
          }
        }
        // 开启了密码填写
        if (res.data && res.data.passwordWriteStatus) {
          this.writeStatus = 3
        }
      }
      return res
    },
    handleCheckWritePwd() {
      checkWritePwdRequest({
        formKey: this.formKey,
        password: this.writePassword
      }).then((res) => {
        this.writeStatus = 1
      })

    },
    handleFormLoadCompleted() {
      this.$refs.goodsPay.wxJsApiPay()
    },
    async submitForm(data) {
      console.log(data,'data-----write--index')
      if (this.$refs.goodsPay.openPay(data, this.formKey)) {
        return
      }

      // 完成时间
      this.submitFormData.completeTime = document.getElementById('inActiveTime').innerText
      this.submitFormData.wxUserInfo = this.wxUserInfo
      this.submitFormData.wxOpenId = this.wxUserInfo ? this.wxUserInfo.openid : ''
      this.submitFormData.originalData = data.formModel
      this.submitFormData.formKey = this.formKey
      this.submitFormData.formId = data.formId
      this.submitFormData.formType = this.$refs.bizProjectForm.formConf.formType
      this.submitFormData.accessTime = data.accessTime
      this.submitFormData.submitPhoneNumber = data.submitPhoneNumber
      if(getQueryString('ybk')){
        this.submitFormData.ybkValue=getQueryString('ybk')
      }
      if(getQueryString('ext')){
        this.submitFormData.extValue=getQueryString('ext')
      }
      let res = null
      if (this.writeType === 1) {
        res = await publicCreateFormResultRequest(this.submitFormData)
      } else {
        res = await createFormResultRequest(this.submitFormData)
      }
      console.log(res,'res----11111')
      if(res.data){
        this.formDataId=res.data.id
      }
      this.submitResult = res.data
      // 删除临时缓存数据
      removeFormData(this.formKey)
      Cookies.remove('isLogin')
      if(this.statusFlag == '10'){
        this.isNeedLoginFun()
      }else{
        if(this.formDataId){
          this.writeStatus=2
        }else{
          this.writeStatus=4
        }
        
      }
      
      if (this.userFormSetting.submitJump) {
        setTimeout(() => {
          window.location.replace(this.userFormSetting.submitJumpUrl)
        }, 3000)
      }
    },
    timer() {
      if (this.second > 0) {
        this.second--
        setTimeout(this.timer, 1000)
      } else{
        this.second=0
      }
    },
    getCode(){
      if(this.form.phoneNumber){
        sendCode({
          formKey:this.formKey,
          phoneNumber:this.form.phoneNumber
        }).then((res) => {
          if(res.code == 200){
            this.second=120
            this.timer()
          }else if(res.code == 501){//该手机号已提交过数据，不可重复提交。
            this.writeStatus=4
            this.dialogFormVisible=false
          }else if(res.code == 502){
            this.writeStatus=5
            this.dialogFormVisible=false
          }
        }).catch(()=>{
          this.second=0
        })
      }
        
    },
    login(){
        var param={
          formKey:this.formKey,
          ...this.form
        }
        userFormLogin(param).then((res) => {
          if(res.code == 200){
            if(res.data){
              this.formConfig.submitPhoneNumber=this.form.phoneNumber
              Cookies.set('isLogin', JSON.stringify({phoneNumber:this.form.phoneNumber,formKey:this.formKey,ext:getQueryString('ext') ? getQueryString('ext') : ''}))
              this.dialogFormVisible = false
              if(this.statusFlag == '10'){
                updatePhone({
                  formDataId:this.formDataId,
                  phoneNum:this.form.phoneNumber
                }).then(() => {
                  this.second=120
                  this.timer()
                  if(this.submitResult && this.submitResult.id){
                    this.writeStatus=2
                  }
                }).catch(()=>{
                  this.second=0
                  this.dialogFormVisible=false
                  if(this.submitResult && this.submitResult.id){
                    this.writeStatus=2
                  }
                })
              }else{
                this.start=true
              }
            }else{
              this.start=false
              this.$message.error('登录失败')
            }
          }else if(res.code == 501){//该手机号已提交过数据，不可重复提交。
            this.writeStatus=4
            this.dialogFormVisible=false
          }
        }).catch(()=>{  
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.write-container {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow-x: hidden;
}

.title-icon-view {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;
  width: 100%;
}


.icon-view {
  width: 59px;
  height: 59px;
  border-radius: 100px;
  background-color: #0076ff;
  display: flex;
  align-content: center;
  align-items: center;
  justify-content: center;
}

.success-icon {
  text-align: center;
  color: white;
  font-size: 30px;
}

.pwdinput-card {
  width: 350px;
  margin: 200px auto;
  min-height: 200px;
}
</style>
